package com.mystyle.le.qjnewsproject;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.mystyle.le.qjnewsproject.fragment.CommentFragment;
import com.mystyle.le.qjnewsproject.fragment.NewsFragment;
import com.mystyle.le.qjnewsproject.fragment.PictureFragment;
import com.mystyle.le.qjnewsproject.fragment.TestFragment;

import java.util.ArrayList;
import java.util.List;

public class HelloActivity extends AppCompatActivity {

    private RadioGroup radioGroup;
    private List<Fragment> list = new ArrayList<>();
    private int current;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello);

        initView();
        initFragment();
    }

    private void initFragment() {
        NewsFragment newsFragment = new NewsFragment();
        TestFragment testFragment = new TestFragment();
        PictureFragment pictureFragment = new PictureFragment();
        CommentFragment commentFragment = new CommentFragment();
        list.add(newsFragment);
        list.add(testFragment);
        list.add(pictureFragment);
        list.add(commentFragment);
        //默认提交第一个
        getSupportFragmentManager().beginTransaction().add(R.id.news_title,newsFragment).commit();

    }

    private void initView() {
        radioGroup = ((RadioGroup) findViewById(R.id.news_rg));
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.news:
                        changeFragment(0);
                        break;
                    case R.id.test:
                        changeFragment(1);
                        break;
                    case R.id.picture:
                        changeFragment(2);
                        break;
                    case R.id.comment:
                        changeFragment(3);
                        break;

                }
            }
        });
    }

    private void changeFragment(int position) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        Fragment targetFragment = list.get(position);
        Fragment currentFragment = list.get(current);
        if (targetFragment.isAdded()){
            fragmentTransaction.show(targetFragment).hide(currentFragment).commit();
        }else {
            fragmentTransaction.add(R.id.news_title,targetFragment).hide(currentFragment).commit();
        }
        current = position;
    }
}
